package com.wfh.frp.server;

import com.wfh.frp.coder.ProxMsgEncoder;
import com.wfh.frp.coder.ProxyMsgDecoder;
import com.wfh.frp.handler.ServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @Title: MainServer
 * @Author wangfenghuan
 * @Package com.wfh.frp.server
 * @Date 2025/10/8 10:51
 * @description: 主服务节点
 */
@Slf4j
public class MainServer {

    public static final EventLoopGroup boss = new NioEventLoopGroup(1);

    public static final EventLoopGroup work = new NioEventLoopGroup();

    /**
     * 开启主代理服务
     * @param port 端口号
     */
    public static void start(int port){
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boss, work);
            serverBootstrap.channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline()
                                     .addLast(new ProxyMsgDecoder())
                                     .addLast(new ProxMsgEncoder())
                                     .addLast(new IdleStateHandler(60, 30, 0, TimeUnit.SECONDS))
                                    // .addLast( new HttpObjectAggregator(65535))
                                    .addLast(new ServerHandler());

                        }
                    });
            ChannelFuture sync = serverBootstrap.bind(port).sync();
            log.info("Proxy Server is listening on port : {}", port);
            sync.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            work.shutdownGracefully();
        }
    }

    /**
     * 开启主代理服务，使用默认端口9090
     */
    public static void start() {
        start(DEFAULT_PORT);
    }

    private static final int DEFAULT_PORT = 9090;

}
